import { Forward } from "@/api/interface/iot";
import Empty from "@/components/Empty";
import { addRule, modRule, getRuleList, delRule } from "@/api/modules/forward/forwardRule";
import ProTable from "@/components/ProTable/index.vue";
import { ColumnProps } from "@/components/ProTable/interface";
import { MessageType } from "@/enums/messageEnum";
import { useAuthButtons } from "@/hooks/useAuthButtons";
import { dataFormat } from "@/utils/format";
import { confirm, showMsg, showTips } from "@/utils/util";
import BasicDialog from "./components/ruleDialog";
import { ComponentInternalInstance, getCurrentInstance } from "vue";
export default defineComponent({
	setup() {
		const { proxy } = getCurrentInstance() as ComponentInternalInstance;
		const initParam = reactive<Forward.ReqServer>({});

		const dataCallback = (data: any) => {
			return {
				datalist: data.records,
				total: data.total || 0,
				pageIndex: data.current,
				pageSize: data.size
			};
		};

		const getTableList = async (params: any) => {
			return getRuleList(params);
		};
		const btnList = ref<any>([]);
		onMounted(async () => {
			// 获取页面按钮权限
			btnList.value = await useAuthButtons();
		});
		const detailDialog = reactive<any>({
			title: proxy?.$t("forwardrule.dialog_title.add"),
			detail: { targetType: "product", serverType: "MQTT" },
			visible: false
		});
		const clickBtn = async (fn: string, row: any) => {
			let selected = row.selectList || [row];
			switch (fn) {
				case "mod":
				case "details":
					if (selected.length != 1) {
						showMsg(proxy?.$t("forwardrule.msg.details"), MessageType.warning);
						return;
					}
					let detail = JSON.parse(JSON.stringify(selected[0]));
					detail.targetType = detail.devSn ? "device" : "product";
					detail.variableMap = JSON.stringify(detail.variableMap);
					detailDialog.title = proxy?.$t("forwardrule.dialog_title.mod");
					detailDialog.detail = detail;
					detailDialog.visible = true;
					break;
				case "add":
					detailDialog.detail = { targetType: "product", serverType: "MQTT" };
					detailDialog.title = proxy?.$t("forwardrule.dialog_title.new");
					detailDialog.visible = true;
					break;
				case "del":
					if (!selected.length) {
						showMsg(proxy?.$t("forwardrule.msg.del"), MessageType.warning);
						return;
					}
					confirm({ content: proxy?.$t("forwardrule.confirm.del") }).then(flag => {
						flag && submitDel({ id: selected.map((item: any) => item.id).join(",") });
					});
					break;
			}
		};
		// 表格配置项
		const columns: ColumnProps[] = [
			{ type: "selection", fixed: "left", width: "auto" },
			{ prop: "name", label: proxy?.$t("forwardrule.tablist_label.name"), search: { el: "input" } },
			{ prop: "productModel", label: proxy?.$t("forwardrule.tablist_label.product"), search: { el: "input" }, isShow: false },
			{ prop: "devSn", label: proxy?.$t("forwardrule.tablist_label.devsn"), search: { el: "input" }, isShow: false },
			{ prop: "server", label: proxy?.$t("forwardrule.tablist_label.server") },
			{ prop: "serverType", label: proxy?.$t("forwardrule.tablist_label.server_type"), search: { slot: {} } },
			{ prop: "target", label: proxy?.$t("forwardrule.tablist_label.target") },
			{ prop: "modelSN", label: proxy?.$t("forwardrule.tablist_label.modelsn") },
			{ prop: "createTime", label: proxy?.$t("forwardrule.tablist_label.create_time") },
			{ prop: "operation", label: proxy?.$t("forwardrule.tablist_label.operation"), fixed: "right", width: 130 }
		];

		const proTable = ref<any>();
		const submitDel = async (dataInfo: any) => {
			let res = await delRule({ ...dataInfo });
			let ok = showTips(res.code, proxy?.$t("forwardrule.tips.del"), res.message);
			if (ok) {
				proTable.value.clearSelection();
				proTable.value.reset();
			}
		};
		const submit = async () => {
			let detail = JSON.parse(JSON.stringify(detailDialog.detail));
			detail.variableMap = JSON.parse(detail.variableMap);
			detail.serverId = detail.server.id;
			let api = detailDialog.detail.id ? modRule : addRule;
			let res = await api(detail);
			let ok = showTips(res.code, proxy?.$t("forwardrule.tips.save"), res.message);
			if (ok) {
				detailDialog.visible = false;
				proTable.value.getTableList();
			}
		};
		return () => {
			return (
				<div>
					{detailDialog.title && (
						<BasicDialog
							width="700px"
							title={detailDialog.title}
							v-model:visible={detailDialog.visible}
							detail={detailDialog.detail}
							onSubmit={() => submit()}
						></BasicDialog>
					)}
					<ProTable
						ref={proTable}
						title={btnList.value.length ? "" : proxy?.$t("forwardrule.tab_title.manage")}
						columns={columns}
						requestApi={getTableList}
						initParam={initParam}
						dataCallback={dataCallback}
					>
						{{
							"search-serverType": () => {
								return (
									<el-select v-model={initParam.serverType} style="width:100px">
										<el-option label={proxy?.$t("forwardrule.option.all")} value=""></el-option>
										<el-option label="MQTT" value="MQTT"></el-option>
										<el-option label="HTTP" value="HTTP"></el-option>
										<el-option label="DB" value="DB"></el-option>
									</el-select>
								);
							},
							tableHeader: (scope: any) => {
								return btnList.value?.map((item: any) => {
									return (
										<el-button onClick={() => clickBtn(item.path, scope)} type={item.btnClass}>
											<i class={`iconfont ${item.icon}`}></i>
											{item.menuName}
										</el-button>
									);
								});
							},
							createTime: (scope: any) => {
								return dataFormat("datetime", scope.row.createTime);
							},
							target: (scope: any) => {
								return scope.row.devSn ? (
									<el-tag>{proxy?.$t("forwardrule.target.dev")}</el-tag>
								) : (
									<el-tag type="success">{proxy?.$t("forwardrule.target.product")}</el-tag>
								);
							},
							modelSN: (scope: any) => {
								return scope.row.devSn ? scope.row.devSn : scope.row.productModel;
							},
							server: (scope: any) => {
								return (
									<el-popover
										show-after={500}
										width="250"
										placement="top-start"
										title={proxy?.$t("forwardrule.popover.title")}
										trigger="hover"
									>
										{{
											default: () => {
												return (
													<div class="leading-6">
														<div class="flex items-center">
															<div class="label">{proxy?.$t("forwardrule.popover_label.type")}</div>
															<div>{scope.row.server?.type}</div>
														</div>
														<div class="flex items-center">
															<div class="label">{proxy?.$t("forwardrule.popover_label.host")}</div>
															<div>{scope.row.server?.host}</div>
														</div>
														<div class="flex items-center">
															<div class="label">{proxy?.$t("forwardrule.popover_label.port")}</div>
															<div>{scope.row.server?.port}</div>
														</div>
													</div>
												);
											},
											reference: () => {
												return (
													<div>
														<i class="iconfont iconbx-info-circle"></i>
														<span class="pl-1">{scope.row.server?.name}</span>
													</div>
												);
											}
										}}
									</el-popover>
								);
							},
							operation: (scope: any) => {
								return (
									<>
										{btnList.value
											.filter((item: any) => item.path == "del")
											.map((item: any) => {
												return (
													<el-popconfirm
														title={proxy?.$t("forwardrule.popconfitm.title")}
														popper-class="jsonform-tooltip"
														onConfirm={() => submitDel({ id: scope.row.id })}
													>
														{{
															reference: () => {
																return (
																	<el-link type="danger">
																		<i class="iconfont icontrash-2"></i>
																		{item.menuName}
																	</el-link>
																);
															}
														}}
													</el-popconfirm>
												);
											})}
										{!btnList.value.find((item: any) => item.path == "del") ? (
											<el-link type="danger" disabled>
												<i class="iconfont icontrash-2"></i>
												{proxy?.$t("forwardrule.link.delete")}
											</el-link>
										) : null}
										<el-link type="primary" class="iconfont iconbx-file" onClick={() => clickBtn("details", scope.row)}>
											{proxy?.$t("forwardrule.link.detail")}
										</el-link>
									</>
								);
							},
							empty: (scope: any) => {
								return (
									<Empty
										title={proxy?.$t("forwardrule.empty.title")}
										subtitle={proxy?.$t("forwardrule.empty.subtitle")}
										onAdd={() => clickBtn("add", scope.row || {})}
									/>
								);
							}
						}}
					</ProTable>
				</div>
			);
		};
	}
});
